package com.scm.service.impl;

import java.util.List;

import com.scm.common.core.domain.entity.SysUser;
import com.scm.common.enums.OrderOperationType;
import com.scm.common.enums.OrderStatus;
import com.scm.common.utils.DateUtils;
import com.scm.common.utils.StringUtils;
import com.scm.converter.OrderConverter;
import com.scm.dto.resp.order.*;
import com.scm.factory.OrderProductFactory;
import com.scm.persist.model.*;
import com.scm.persist.mybatis.ScmOrderLogMapper;
import com.scm.persist.mybatis.ScmOrderMapper;
import com.scm.persist.mybatis.ScmOrderOperationMapper;
import com.scm.persist.mybatis.ScmOrderProductMapper;
import com.scm.service.IScmOrderLogService;
import com.scm.service.IScmOrderService;
import com.scm.system.service.ISysUserService;
import org.apache.commons.compress.utils.Lists;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.springframework.util.CollectionUtils;

/**
 * 订单主Service业务层处理
 *
 * @author reptilemanager
 * @date 2024-02-08
 */
@Service
public class ScmOrderServiceImpl implements IScmOrderService
{
    @Autowired
    private ScmOrderMapper scmOrderMapper;

    @Autowired
    private ScmOrderLogMapper scmOrderLogMapper;

    @Autowired
    private IScmOrderLogService orderLogService;

    @Autowired
    private ScmOrderOperationMapper scmOrderOperationMapper;

    @Autowired
    private ScmOrderProductMapper scmOrderProductMapper;

    @Autowired
    private OrderProductFactory orderProductFactory;



    @Autowired
    private ISysUserService userService;

    /**
     * 查询订单主
     *
     * @param id 订单主主键
     * @return 订单主
     */
    @Override
    public ScmOrder selectScmOrderById(Long id)
    {
        OrderDetailDo orderDetailDo = new OrderDetailDo();
        ScmOrder scmOrder = scmOrderMapper.selectByPrimaryKey(id);

        return scmOrder;
    }

    @Override
    public void syncProudct(Long id) {



    }

    /**
     * 查询订单主列表
     *
     * @param scmOrder 订单主
     * @return 订单主
     */
    @Override
    public QueryOrderPageResp selectScmOrderList(ScmOrder scmOrder , Integer start, Integer size ,SysUser sysUser)
    {
        ScmOrderExample example = new ScmOrderExample ();
        example.createCriteria().andTenantIdEqualTo(sysUser.getTenantId());
        List<OrderPageDo> orderPageDoList = Lists.newArrayList();
        int count = scmOrderMapper.countByExample(example);

        if(count>0){

            RowBounds rowBounds = new RowBounds(start,size);

            List<ScmOrder> list = scmOrderMapper.selectByExampleWithRowbounds(example,rowBounds);

            if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)){

                for (ScmOrder order : list) {

                    ScmOrderOperation scmOrderOperation =  selectByScmOrderId(order.getId());

                    OrderPageDo orderPageDo = OrderConverter.convertSCMSOrdersToOrderPage(order);

                    if(StringUtils.isNotEmpty(scmOrderOperation.getZhipairen())){
                        SysUser zhipaiUser =  userService.selectUserById(Long.valueOf(scmOrderOperation.getZhipairen()));

                        orderPageDo.setZhipaiUserId(zhipaiUser.getUserId());
                        orderPageDo.setZhipaiUserName(zhipaiUser.getUserName());

                    }


                    orderPageDoList.add(orderPageDo);


                }
            }

        }

        return QueryOrderPageResp.builder().list(orderPageDoList).total(count).build();

    }

    @Override
    public List<OrderProductDo> selectScmOrderProductList(Long tenantId,Long orderId) {

        ScmOrderProductExample example = new ScmOrderProductExample();
        example.createCriteria().andScmOrderIdEqualTo(orderId);
        List<ScmOrderProduct>  list = scmOrderProductMapper.selectByExample(example);
        List<OrderProductDo> orderProductDos = orderProductFactory.createOrderProductDos(tenantId,list);
        return orderProductDos;
    }

    @Override
    public List<ScmOrderLogDO> selectScmOrderLogList(Long tenantId, Long orderId) {

        ScmOrderLogExample example = new ScmOrderLogExample();
        example.createCriteria().andScmOrderIdEqualTo(orderId).andTenantIdEqualTo(tenantId);

        List<ScmOrderLog> list = scmOrderLogMapper.selectByExample(example);

        List<ScmOrderLogDO> result = Lists.newArrayList();
        if(org.apache.commons.collections4.CollectionUtils.isNotEmpty(list)){
            for (ScmOrderLog scmOrderLog : list) {

                ScmOrderLogDO orderLogDO = new ScmOrderLogDO();
                orderLogDO.setId(scmOrderLog.getId());
                orderLogDO.setTenantId(scmOrderLog.getTenantId());
                orderLogDO.setScmOrderId(scmOrderLog.getScmOrderId());
                orderLogDO.setOperationType(scmOrderLog.getOperationType());
                orderLogDO.setOperationTypeDesc(scmOrderLog.getOperationTypeDesc());
                orderLogDO.setOperatorId(scmOrderLog.getOperatorId());
                orderLogDO.setOperator(scmOrderLog.getOperator());
                orderLogDO.setRemark(scmOrderLog.getRemark());
                orderLogDO.setCreateTimeStr(DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",scmOrderLog.getCreateTime()));

                result.add(orderLogDO);
            }
        }

        return result;
    }

    /**
     * 新增订单主
     *
     * @param scmOrder 订单主
     * @return 结果
     */
    @Override
    public long insertScmOrder(ScmOrder scmOrder,SysUser sysUser )
    {
        scmOrder.setCreateTime(System.currentTimeMillis());

        long id = scmOrderMapper.insertSelective(scmOrder);

        ScmOrderLog orderLog = OrderConverter.createOrderLog(id, OrderOperationType.Create,sysUser,sysUser.getLoginName()+"创建订单，订单id为：（"+id+"）");
        orderLogService.saveOrderLog(orderLog);
        return id;
    }


    /**
     * 修改订单主
     *
     * @param scmOrder 订单主
     * @return 结果
     */
    @Override
    public int updateScmOrder(ScmOrder scmOrder,SysUser sysUser)
    {
        scmOrder.setUpdateUser(String.valueOf(sysUser.getUserId()));
        scmOrder.setUpdateTime(System.currentTimeMillis());

        int i = scmOrderMapper.updateByPrimaryKeySelective(scmOrder);

        return i;
    }


    /**
     * 删除订单主信息
     *
     * @param id 订单主主键
     * @return 结果
     */
    @Override
    public int deleteScmOrderById(Long id)
    {
        return scmOrderMapper.deleteByPrimaryKey(id);
    }


    @Override
    public int confirmOrder(Long id, SysUser sysUser) {



        return 0;
    }

    public Long saveOrUpdateScmOrder(SysUser sysUser,ScmOrder scmOrder){

        ScmOrderExample example = new ScmOrderExample();
        example.createCriteria().andOrderidEqualTo(scmOrder.getOrderid()).andOrderSourceEqualTo(scmOrder.getOrderSource());

        int count = scmOrderMapper.countByExample(example);
        if(count>0){
            //更新
            scmOrder.setUpdateTime(System.currentTimeMillis());
            scmOrder.setUpdateUser(String.valueOf(sysUser.getUserId()));
            scmOrderMapper.updateByExampleSelective(scmOrder,example);
        }else{
            //插入
            scmOrder.setCreateTime(System.currentTimeMillis());
            scmOrder.setCreateUser(String.valueOf(sysUser.getUserId()));
            scmOrderMapper.insertSelective(scmOrder);

            ScmOrderOperation record = new ScmOrderOperation();
            record.setScmOrderId(scmOrder.getId());
            record.setCreateTime(System.currentTimeMillis());
            record.setCreateUser(String.valueOf(sysUser.getUserId()));
            scmOrderOperationMapper.insertSelective(record);
        }

        return scmOrder.getId();
    }


    @Override
    public ScmOrderOperation selectByScmOrderId(Long scmOrderId) {

        List<ScmOrderOperation> scmOrderOperations = scmOrderOperationMapper.selectByScmOrderId(scmOrderId);

        if(!CollectionUtils.isEmpty(scmOrderOperations)){
            ScmOrderOperation scmOrderOperation = scmOrderOperations.get(0);
            return scmOrderOperation;
        }
        return null;
    }

    @Override
    public void updateBaobeiStatus(String omsOrderId) {

        ScmOrderExample example = new ScmOrderExample();
        example.createCriteria().andOrderidEqualTo(omsOrderId).andOrderSourceEqualTo("OMS");
        ScmOrder record = new ScmOrder();
        record.setBaobeiStatus("1");
        scmOrderMapper.updateByExampleSelective(record,example);

    }

    @Override
    public void updateOrderStatus(Long scmOrderId, OrderStatus orderStatus) {

        ScmOrderExample example = new ScmOrderExample();
        example.createCriteria().andIdEqualTo(scmOrderId);
        ScmOrder record = new ScmOrder();
        record.setOrderStatus(orderStatus.getCode());
        scmOrderMapper.updateByExampleSelective(record,example);

    }

    @Override
    public int updateScmOrderOperation(ScmOrderOperation scmOrderOperation) {

        return  scmOrderOperationMapper.updateByScmOrderId(scmOrderOperation, scmOrderOperation.getScmOrderId());
    }
}
